<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <HeaderView @onAdd="onAdd" />
        <ListView v-show="todoList.length" :todoList="todoList" />
        <FooterView
          v-show="todoList.length" 
          :todoList="todoList" 
          @allCheck="allCheck" 
          @onAllDelete="onAllDelete"
        />
      </div>
    </div>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'
import HeaderView from './components/HeaderView.vue'
import ListView from './components/ListView.vue'
import FooterView from './components/FooterView.vue'

export default {
    name: 'App',
    components:{
      HeaderView,
      ListView,
      FooterView
    },
    data() {
      return {
        todoList: JSON.parse(localStorage.getItem('data')) || []
      }
    },
    methods: {
      onAdd(info) {
        this.todoList.unshift(info)
      },
      // onCheck(id) {
      //   this.todoList.forEach(todo => {
      //     if (todo.id === id) todo.done = !todo.done
      //   });
      // },
      updateTodo(id, name) {
        this.todoList.forEach(todo => {
          if (todo.id === id) todo.name = name
        });
      },
      onDeleteById(id) {
        this.todoList = this.todoList.filter(todo => todo.id != id)
      },
      allCheck(done) {
        this.todoList.forEach(todo => {
          todo.done = done
        });
      },
      onAllDelete() {
        this.todoList = this.todoList.filter(todo => !todo.done)
      }
    },
    watch: {
      todoList: {
        deep: true,
        handler(newValue) {
          localStorage.setItem('data', JSON.stringify(newValue))
        }
      }
    },
    mounted() {
      this.$bus.$on('onCheck', (id) => {
        this.todoList.forEach(todo => {
          if (todo.id === id) todo.done = !todo.done
        });
      })
      this.$bus.$on('updateTodo', this.updateTodo)
      // this.$bus.$on('onDeleteById', this.onDeleteById)
      this.pid = pubsub.subscribe('onDeleteById', (_, id) => this.onDeleteById(id))
    },
    beforeDestroy() {
      this.$bus.$off('onCheck')
      this.$bus.$off('updateTodo')
      pubsub.unsubscribe(this.pid)
    }
}
</script>

<style lang="less">
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}
.btn-edit {
  color: #fff;
  background-color: skyblue;
  border: 1px solid skyblue;
  margin-right: 10px;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

</style>